package functions

import (
	"fmt"

	"github.com/project-flogo/core/data"
	"github.com/project-flogo/core/data/coerce"

	"github.com/project-flogo/core/data/expression/function"
)

func init() {
	err := function.Register(&fnFormatCanboat{})
	if err != nil {
		panic(err)
	}
}

type fnFormatCanboat struct{}

func (fnFormatCanboat) Name() string {
	return "formatCanboat"
}

func (fnFormatCanboat) Sig() (paramsTypes []data.Type, isVariadic bool) {
	return []data.Type{data.TypeString}, false
}

func (fnFormatCanboat) Eval(params ...interface{}) (interface{}, error) {
	payload, err := coerce.ToBytes(params[0])
	if err != nil {
		return nil, fmt.Errorf("formatCanboat function parameter [%+v] must be bytes", params[0])
	}
	if len(payload) != 12 {
		return nil, fmt.Errorf("fortmatCanboat funtion parameter must be bytes of 12, got: %d", len(payload))
	}
	offset := 0
	s := fmt.Sprintf(
		"<0x%02x%02x%02x%02x> [8] %02x %02x %02x %02x %02x %02x %02x %02x",
		payload[offset+0],
		payload[offset+1],
		payload[offset+2],
		payload[offset+3],
		payload[offset+4],
		payload[offset+5],
		payload[offset+6],
		payload[offset+7],
		payload[offset+8],
		payload[offset+9],
		payload[offset+10],
		payload[offset+11])
	return s, nil
}
